﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Chat.Models;
using Chat.Models.Services;
using Chat.Filters;
using System.IO;
using OpenTokSDK;

namespace Chat.Controllers
{
    public class ApiController : Controller
    {
        // GET: Api
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        
        public ActionResult Login(string phoneNumber, string passwd)
        {
            if (string.IsNullOrEmpty(phoneNumber)|| string.IsNullOrEmpty(passwd))
            {
                return Json(
                   new
                   {
                       Code = 202,
                       Mes = "密码或账户为空",
                       Token = "",
                   });
            }

            var user = UserService.GetUserByPhoneNumberAndPassword(phoneNumber, passwd);
            if (user != null)
            {
                return Json(
                    new
                    {
                        Code = 200,
                        Mes = "成功",
                        Token = UserService.GetLoginToken(user.UserID),
                    });
            }
            return Json(
                    new
                    {
                        Code = 201,
                        Mes = "失败",
                        Token = "",
                    });

        }

        [HttpPost]
        public ActionResult Regist(RegistMoudel registMoudel)
        {
            if (!ModelState.IsValid)
            {
                return Json(
                    new{
                        Code = 203,
                        Mes = "失败,缺少参数",
                    });
            }

            var user = UserService.GetUsersByPhoneNumber(registMoudel.PhoneNumber);
            if (user != null)
            {
                return Json(
                    new
                    {
                        Code = 205,
                        Mes = "失败，手机号已经注册过了",
                    });
            }

            if (UserService.addUser(registMoudel))
            {
                return Json(
                   new
                   {
                       Code = 200,
                       Mes = "成功",
                   });
            }

            return Json(
                   new
                   {
                       Code = 207,
                       Mes = "失败,数据存入失败",
                   });

        }
        [ApiAuthFilter]
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase imageFile)
        {
            if (imageFile != null && imageFile.ContentLength > 0)
            {
                // 生成随机文件名
                string randomFileName = Guid.NewGuid().ToString();

                // 获取原始文件的后缀名
                string fileExtension = Path.GetExtension(imageFile.FileName);

                // 合并随机文件名和原始后缀名，保存到 ~/Uploads 目录
                string fileName = Path.Combine(Server.MapPath("~/Uploads"), randomFileName + fileExtension);

                imageFile.SaveAs(fileName);

                return Json(new
                {
                    Code=200,
                    Meg="成功",
                    FileNmae= "/Uploads/"+randomFileName + fileExtension
                });
            }
            return Json(new
            {
                Code = 210,
                Meg = "失败",
                FileName=""
            });

        }

        [ApiAuthFilter]
        [HttpPost]
        public ActionResult getFriendAndLastMessage()
        {
            string token = HttpContext.Request.Headers["token"];
            int userID = TokenStore.GetCachedData(token).UserID;
            var indexdata = UserService.getIndexData(userID);

            return Json(indexdata);
            
        }


        [ApiAuthFilter]
        [HttpPost]
        public ActionResult getChatMessagesWithFriend(int FriendId)
        {
            string token = HttpContext.Request.Headers["token"];
            int userID = TokenStore.GetCachedData(token).UserID;


            var friendship = UserService.GetFriendshipsByUserIDAAndUserB(userID, FriendId);
            if (friendship == null)
            {
                return Json(new
                {
                    Code = 210,
                    Mes = "不是好友",
                    ChatMessages = friendship//null
                });
            }


            var chatMessages = ChatMessageService.getChatMessagesWithFriend(userID, FriendId);
            return Json(new
            {

                Code = 200,
                Mes = "success",
                ChatMessages = chatMessages.Count == 0 ? new List<ChatMessages>() : chatMessages.ToList()
            });
        }
        [ApiAuthFilter]
        [HttpPost]
        public ActionResult addFriend(int FriendId)
        {
            string token = HttpContext.Request.Headers["token"];
            int userID = TokenStore.GetCachedData(token).UserID;


            var friendship = UserService.GetFriendshipsByUserIDAAndUserB(userID, FriendId);
            if (friendship != null)
            {
                return Json(new
                {
                    Code = 210,
                    Meg = "已经是好友了",
                });
            }
             bool success =UserService.AddFriend(userID, FriendId);

            return Json(new
            {
                Code = success ? 200 : 210,
                Meg = success ? "添加好友成功" : "添加好友失败"
            });
        }

        [HttpPost]
        public ActionResult GetUserByUserId(int userId)
        {

            var user = UserService.GetUsersByUserId(userId);
            return Json(new
            {
                Code = user == null ? 201 : 200,
                Meg = user == null ? "无此人" : "success",
                User = user
            });
        }

        [ApiAuthFilter]
        [HttpPost]
        public ActionResult sendChatMessage(ChatMessages chatMessage)
        {

            string token = HttpContext.Request.Headers["token"];
            int userID = TokenStore.GetCachedData(token).UserID;
            if(userID != chatMessage.SenderID)
            {
                return Json(new
                {
                    Code = 210,
                    Mes = "只能发送自己的消息"
                });
            }

            var success = ChatMessageService.addChatMessage(chatMessage);

            return Json(new
            {
                Code = success ? 200 : 210,
                Meg = success ? "成功" : "失败"
            });
        }

        [ApiAuthFilter]
        [HttpPost]
        public ActionResult GetSelfUserId()
        {
            string token = HttpContext.Request.Headers["token"];
            int userId = TokenStore.GetCachedData(token).UserID;

            var user = UserService.GetUsersByUserId(userId);
            return Json(new
            {
                Code = user == null ? 201 : 200,
                Meg = user == null ? "无此人" : "success",
                User = user
            });
        }

        [ApiAuthFilter]
        [HttpPost]
        public ActionResult updateUserByUserId(Users newUser)
        {
            string token = HttpContext.Request.Headers["token"];
            int userID = TokenStore.GetCachedData(token).UserID;

            if (UserService.updateUserById(userID, newUser))
            {
                return Json(new
                {
                    Code = 200,
                    Mes = "成功"
                });
            }
            return Json(new
            {
                Code = 210,
                Mes = "失败"
            });
        }

        [ApiAuthFilter]
        [HttpPost]
        public ActionResult auth()
        {
            return Json(
                new
                {
                    Code = 200,
                    Meg = "拥有权限"
                });
            
        }

        public ActionResult getUserByPhoneNumber(string phoneNumber)
        {
            
            var user = UserService.GetUserByPhoneNumber(phoneNumber);

            return Json(new
            {
                Code = user == null ? 201 : 200,
                Meg = user == null ? "无此人" : "success",
                User = user
            });
        }

        [ApiAuthFilter]
        [HttpPost]
        public ActionResult giveLike(int uid)
        {

             UserService.GiveALike(uid);

            return Json(new
            {
                Code = 200,
                Meg = "success",
            });
        }

        public ActionResult getOpenTokSession()
        {
            var OpenTok = new OpenTok(47840281, "7fdec8e6bd58c0ecc5f3133ff9a4c40eda84bc76");
            var session = OpenTok.CreateSession();
            string sessionId = session.Id;

            double inOneWeek = (DateTime.UtcNow.Add(TimeSpan.FromDays(7)).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            string tokenA = session.GenerateToken(role: Role.PUBLISHER, expireTime: inOneWeek);

            string tokenB = session.GenerateToken(role: Role.PUBLISHER, expireTime: inOneWeek);

            return Json(new
            {
                SessionId=sessionId,
                TokenA=tokenA,
                TokenB=tokenB
            });
        }


        public ActionResult test(string token)
        {
            return View();
        }
    }


}